package com.zhejiangzhengyuan.municipal_common.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhejiangzhengyuan.municipal_common.entity.Device;
import com.zhejiangzhengyuan.municipal_common.entity.DeviceData;
import com.zhejiangzhengyuan.municipal_common.entity.WarnEvent;
import com.zhejiangzhengyuan.municipal_common.mapper.DeviceDataMapper;
import com.zhejiangzhengyuan.municipal_common.mapper.DeviceMapper;
import com.zhejiangzhengyuan.municipal_common.service.WarnEventService;
import com.zhejiangzhengyuan.municipal_common.utils.BaseUtil;
import com.zhejiangzhengyuan.municipal_common.utils.ConstantUtil;
import com.zhejiangzhengyuan.municipal_common.utils.httpUtils.HttpServerUtil;
import com.zhejiangzhengyuan.municipal_common.utils.httpUtils.Message;
import com.zhejiangzhengyuan.municipal_common.service.ManholeCoverApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

import java.util.Objects;

import static com.zhejiangzhengyuan.municipal_common.utils.DateFormatUtil.timeFormat;

/**
 * @author lin_ju
 * @create on 2019/11/25
 */
@Service
@Slf4j
public class ManholeCoverApplicationServiceImpl implements ManholeCoverApplicationService {
  @Autowired private DeviceMapper deviceMapper;
  @Autowired private WarnEventService warnEventService;
  @Autowired private DeviceDataMapper deviceDataMapper;

  @Override
  public void isOnline(HttpServletRequest request, String deviceType) throws Exception {
    log.info("收到电信物联网平台数据,device:{}", deviceType);
    Message message = HttpServerUtil.resolveMessage(request);
    JSONObject object = JSON.parseObject(message.getContent());
    String deviceCode = object.getString("deviceId");
    int eventType = object.getInteger("eventType");
    // 获取到对应device
    Device device = deviceMapper.selectByCode(deviceCode, deviceType);
    if (Objects.isNull(device)) {
      return;
    }
    // 记录接收值
    DeviceData data =
        new DeviceData()
            .setCreateTime(timeFormat(System.currentTimeMillis()))
            .setDeviceId(device.getId())
            .setDeviceType(deviceType)
            .setOriginValue(message.getContent());
    deviceDataMapper.insert(data);
    String status = device.getStatus();
    // 异常状态不是在线或离线   则表示 设备进入异常状态
    if (status.equals("在线") || status.equals("离线")) {
      if (eventType == 1) {
        device.setStatus("在线");
      } else {
        device.setStatus("离线");
        // 设备离线告警(井盖系统 与雨污混排同一套设备)
        formatWarnEvent(deviceType, device.getId(), "设备离线");
        device.setWarn(true);
      }
    }
    device.setGeometry(null);
    deviceMapper.updateById(device);
  }

  @Override
  public void fromDeviceResult(HttpServletRequest request, String deviceType) throws Exception {
    log.info("收到电信物联网平台数据,device:{}", deviceType);

    Message message = HttpServerUtil.resolveMessage(request);
    JSONObject object = JSON.parseObject(message.getContent());
    String deviceCode = object.getString("deviceId");
    Device device = deviceMapper.selectByCode(deviceCode, deviceType);
    JSONObject payload = object.getJSONObject("payload");
    //device若已在告警状态不作处理
    if ((Objects.nonNull(device) && !device.isWarn()) && payload.containsKey("APPdata")) {
      // 记录接收值
      DeviceData deviceData =
          new DeviceData()
              .setCreateTime(timeFormat(System.currentTimeMillis()))
              .setDeviceId(device.getId())
              .setDeviceType(deviceType)
              .setOriginValue(message.getContent());
      deviceDataMapper.insert(deviceData);
      String data = payload.getString("APPdata");
      // 通过解密得到16位的字符串
      String binaryBy = BaseUtil.get16BinaryBy(data);
      if (binaryBy.length() != 10) {
        log.warn(">>>>>>>>数据错误 APPdata<<<<<<<<<");
        return;
      }
      // 井盖状态
      String s2 = binaryBy.substring(2, 4);
      // 水位状态
      String s3 = binaryBy.substring(4, 6);
      // 电压值
      //        String s4 = binaryBy.substring(6, 8);
      // 信号强度
      //        String s5 = binaryBy.substring(8, 10);
      if (BaseUtil.byte16to10byte(s2).equals(ConstantUtil.WARN_VALUE.JG_STATIC)
          && BaseUtil.byte16to10byte(s3).equals(ConstantUtil.WARN_VALUE.SW_STATIC)) {
        formatWarnEvent(deviceType, device.getId(), "水位异常且井盖被打开");
      } else if (BaseUtil.byte16to10byte(s2).equals(ConstantUtil.WARN_VALUE.JG_STATIC)) {
        formatWarnEvent(deviceType, device.getId(), "井盖被打开");
      } else if (BaseUtil.byte16to10byte(s3).equals(ConstantUtil.WARN_VALUE.SW_STATIC)) {
        formatWarnEvent(deviceType, device.getId(), "水位异常");
      }
      device.setGeometry(null);
      device.setWarn(true);
      deviceMapper.updateById(device);
    }
  }

  private void formatWarnEvent(String deviceType, Long deviceId, String reason) {
    // 设备离线告警(井盖系统 与雨污混排同一套设备)
    WarnEvent warnEvent =
        new WarnEvent()
            .setReason(reason)
            .setReportUserInfoId(1L)
            .setCreateTime(timeFormat(System.currentTimeMillis()))
            .setLevel("三级")
            .setDataOrigin(ConstantUtil.WARN_DATA_ORIGIN.SYSTEM)
            .setDeviceId(deviceId);
    // 设备报警  通知到监控中心
    // geometry 不能加入修改
    String departmentName = "监控中心";
    if (deviceType.equals(ConstantUtil.DEVICE_TYPE.MANHOLE_COVER)) {
      warnEventService.insertWarnEvent(
          ConstantUtil.MODULE_NAME.MANHOLE_COVER,
          warnEvent,
          ConstantUtil.WARN_TYPE.MANHOLE_COVER,
          departmentName);
    } else {
      warnEventService.insertWarnEvent(
          ConstantUtil.MODULE_NAME.SEWAGE,
          warnEvent,
          ConstantUtil.WARN_TYPE.SEWAGE,
          departmentName);
    }
  }
}
